const common = require('../../../../public.js')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isOverShare: true, //全局分享标识请勿删除
        showPop: false, //选择门票弹框
        actDes: {}, //活动基本信息
        ticketList: null, //门票集合
        price: '', //价格
        surplusNum: '', //名额
        InfoList: [], //返回门票必填信息集合
        value: '', //填写信息值
        shuList: [],
        personage: [], //返回个人信息
        selectPrice: '', //返回选中门票价格
        selectId: '', //返回选中门票id
        lon: '',
        lat: '',
        isLoading: false,
        title: '', // 活动名称
        posterImage: '', // 活动海报
        step: 0,
        flagText: true,
        ticketNum: '',
        signUpList: [
            {
                imgUrl: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/VR/edit-circle-fill.png',
                text: '开始报名',
                timer: '03/24 10:00 ',
                isOpacity:false
            },
            {
                imgUrl: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/VR/timer-fill.png',
                text: '报名截止',
                timer: '03/24 10:00 ',
                isOpacity:false
            },
            {
                imgUrl: 'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/VR/trophy-fill.png',
                text: '活动开始',
                timer: '03/24 10:00 ',
                isOpacity:false
            },
        ]
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this
        console.log(options, "optionsoptionsoptions")
        if (options.q) {
            let scan_url = decodeURIComponent(options.q);
            let video_id = scan_url.match(/\d+/) //提取链接中的数字，也就是链接中的参数id，/\d+/ 为正则表达式
            this.setData({
                actId: video_id[0]
            })

            var that = this;
            common.getLocalUserInfo(function (success, userInfo) {
                if (success) {
                    getApp().getLocation(function (data) {
                        that.setData({
                            lon: data.longitude,
                            lat: data.latitude,
                            actId: that.data.actId,
                            user: userInfo.user,
                            token: userInfo.token,
                            openid: userInfo.openid,
                        }, function () {
                            that.getActDes()
                        })
                    })
                }
            }, true)
            return

        } else {

            this.setData({
                title: options.name,
                actId: options.id ? options.id : 100,
                lon: options.xpoint ? options.xpoint : '',
                lat: options.ypoint ? options.ypoint : '',
                posterImage: options.posterImage ? options.posterImage : ''

            }, () => {
                // that.getActDes()
            })
            common.getLocalUserInfo(function (success, userInfo) {
                if (success) {
                    console.log(userInfo, "6877899999999999")
                    getApp().getLocation(function (data) {
                        that.setData({
                            lon: data.longitude,
                            lat: data.latitude,
                            // actId: options.id,
                            user: userInfo.user,
                            token: userInfo.token,
                            openid: userInfo.openid,
                        }, function () {
                            that.getActDes()
                        })
                    })
                }
            }, true)

            wx.setNavigationBarTitle({
                title: options.name //页面标题为路由参数
            })
        }
    },
    checkAddress() { //点击地址按钮
        const lon = parseFloat(this.data.actDes.xpoint)
        const lat = parseFloat(this.data.actDes.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.title ? this.data.title : null,
            address: this.data.actDes.holdingAddress,
            scale: 18,
            fail: () => {
                common.showToast('无地址信息')
            }
        })
    },
    popShow() { //活动报名弹框
        this.getTicketList()
    },
    //获取活动信息
    getActDes() {
        const that = this
        this.setData({
            isLoading: true
        })
        const param = {
            storeActivityId: that.data.actId,
            xpoint: that.data.lon,
            ypoint: that.data.lat,
            // userId: that.data.user.id
            // xpoint: 117.2632,
            // ypoint:34.79502,
            userId: that.data.user.id ? that.data.user.id : ''
        }
        common.post('/storeActivity/selectActivityById', param, function (res) {
            let detailImage = res.data.detailImgs ? res.data.detailImgs : '';
            // if (detailImage) {
            //     // detailImage = detailImage.replace(/\<img/gi, '<img class="rich-img" ');
            //     // detailImage = JSON.stringify(detailImage).replace(/<img/gi, "<img class='richImg'style='width:auto!important;height:auto!important;max-height:100%;width:100%;'");
            // }
            that.opacityFn(res)
            that.setData({
                signUpList: that.data.signUpList,
                actDes: res.data,
                detailImage,
                title: res.data.title,
                posterImage: res.data.posterImage,
                price: res.data.ticketPrice == 0 ? '免费' : res.data.ticketPrice
            })
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    // 活动进行透明度
    opacityFn(res){
        const that = this
        for (let i = 0; i < that.data.signUpList.length; i++) {
            switch (i) {
                case 0:
                    that.data.signUpList[i].timer = res.data.enrollStartTime
                    break;
                case 1:
                    that.data.signUpList[i].timer = res.data.enrollEndTime
                    break;
                case 2:
                    that.data.signUpList[i].timer = res.data.holdingStarttime
                    break;
            }
            if(i<=Number(res.data.enrollStatus)){
                that.data.signUpList[i].isOpacity = true
            }
        }

        
    },
    //获取活动门票
    getTicketList(e) {
        const tempJson = {
            storeActivityId: this.data.actId
        }
        this.setData({
            isLoading: true
        })
        common.post('/storeActivity/findTicketList', tempJson, (res) => {
            if (res.status === 200) {
                this.setData({
                    ticketList: res.data,
                    showPop: true,
                    step: 0
                })
            } else {
                common.showRequestErrMsg(res)
            }
        }, _ => {
            this.setData({
                isLoading: false
            })
        })
    },
    //获取所要填写信息
    getApplyInfo() {
        this.setData({
            isLoading: true
        })
        common.post(
            '/storeActivity/getApplyInfoList', {
            storeActivityId: this.data.actId
        },

            (res) => {
                if (res.status === 200) {
                    this.setData({
                        step: 1,
                        InfoList: res.data,
                    })
                } else {
                    common.showRequestErrMsg(res)
                }
            },

            () => {
                this.setData({
                    isLoading: false
                })
            }
        )
    },
    //时间转换
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    // 弹框隐藏
    popHide() {
        this.setData({
            showPop: false,
            setp: 0
        })
    },
    //选择填写信息弹框
    selectList(e) {
        console.log(e, "e55555555")
        this.getApplyInfo()
        this.setData({
            selectPrice: e.currentTarget.dataset.item.ticketPrice, //返回选中门票价格
            selectId: e.currentTarget.dataset.item.id,
            ticketNum: e.currentTarget.dataset.item.ticketNum,
        })
    },
    // 获取填写内容信息
    // onChange(event, index) {
    //     // //根据下标对应存储到数组
    //     var index1 = event.currentTarget.dataset['index']
    //     // console.log(event.detail,"event.detailevent.detail")
    //     this.data.shuList[index1] = event.detail
    // },
    onChange(event) {
        // console.log(event,"event,")
        var index1 = event.currentTarget.dataset['index']
        var item = event.currentTarget.dataset['item']
        if (item.id == 353) {
            if (event.detail.length == 11) {
                this.setData({
                    flagText: false
                })
            }
        }
        this.data.shuList[index1] = event.detail
    },
    save() {
        let array = []
        for (let i = 0; i < this.data.InfoList.length; i++) {
            if (this.data.InfoList[i].required == 1) {
                if (this.data.shuList == '') {
                    console.log("进来")
                    common.showToast('请填写报名信息')
                    return
                } else {
                    console.log("chuqqv")
                    const content = this.data.shuList[i]
                    if (common.isEmptyString(content)) {
                        common.showToast('请填写报名信息')
                        return
                    }
                    const obj = {
                        nickName: this.data.InfoList[i].nickName,
                        type: this.data.InfoList[i].type,
                        content
                    }
                    array.push(obj)
                }
            }
        }
        if (this.data.selectPrice == 0) {
            const that = this
            // console.log("免费报名")
            common.postJson(
                '/storeActivityOrder/freePay', {
                storeId: that.data.actDes.storeId,
                activityId: that.data.actDes.id, //活动id
                ticketId: that.data.selectId, //门票id
                buyerUserId: that.data.user.id, //用户信息
                applyinfo: array //报名填写信息
            },
                function (res) {
                    if (res.status == 200) {
                        common.showToast('报名成功')
                        this.setState({
                            show: false,
                            showinfo: false
                        })
                    } else {
                        common.showToast('报名失败')
                    }
                }
            )
        } else {
            // console.log("收费报名")
            const that = this
            common.postJson(
                '/storeActivityOrder/wxpay', {
                storeId: that.data.actDes.storeId,
                payment: that.data.selectPrice,
                activityId: that.data.actDes.id, //活动id
                ticketId: that.data.selectId, //门票id
                buyerUserId: that.data.user.id, //用户信息
                applyinfo: array, //报名填写信息
                nickName: '',
                content: '',
                token: that.data.token,
                username: that.data.user.username,
                ticketNum: 1
            },
                function (res) {
                    console.log(res)
                    if (res.status == 200) {
                        common.wxPayRequest(
                            '/wxxcxPayForUserActivity', {
                            userId: that.data.user.id, //活动id
                            token: that.data.token, //门票id
                            orderId: res.data.id, //用户信息
                            openid: that.data.openid, //报名填写信息
                            token: that.data.token,
                            username: that.data.user.username
                        },

                            function (data) {
                                wx.requestPayment({
                                    'timeStamp': data.data.timeStamp,
                                    'nonceStr': data.data.nonceStr,
                                    'package': data.data.package,
                                    'signType': data.data.signType,
                                    'paySign': data.data.paySign,
                                    'success': function (res) {
                                        common.showToast('支付成功', 'success', 2000)
                                    },
                                    'fail': function (res) {
                                        if (res.errMsg === 'requestPayment:fail cancel') { } else {
                                            common.showToast(res.errMsg, 'none', 2000)
                                        }
                                    }
                                })
                            }
                        )
                    } else {
                        common.showRequestErrMsg(res)
                    }
                }
            )
        }
    },
    toBuy(e) {
        // let {
        //     item
        // } = e.currentTarget.dataset
        // let url = null
        console.log(this.data.actDes)
        // common.gotoGoodsPage(this.data.actDes)

        // switch (this.data.actDes.itemType) {
        //     //1普通商品 2零元购 3团购商品 4惠特汇商品 5店铺活动 6抽奖
        //     case 1: // 1普通商品
        //         common.gotoGoodsPage(item)
        //         break;
        //     case 2: // 2零元购 
        //         url = '/packageC/pages/Zero/Des/index?id=' + item.id + '&name=' + item.title
        //         break;
        //     case 3: // 3团购商品
        //         url = '/pages/crowd/index/index?id=' + item.id
        //         break;
        //     case 4: // 4惠特汇商品 
        //         common.gotoGoodsPage(item, '&isVip=true')
        //         break;
        //     case 5: // 5店铺活动
        //         url = '/pages/Activity/actDes/index?id=' + item.id + '&name=' + item.title + '&isVip=true'
        //         break;
        //     case 6: // 6抽奖
        //         url = '/pages/draw/index?drawId=' + item.id
        //         break;
        //     default:
        //         break;
        // }
        // if (url) {
            wx.navigateTo({
                // url: `/packageA/pages/Goods/GoodsDes/index?id=${this.data.actDes.storeId}`
                url:'/packageA/pages/Goods/storePage/index?id=' + this.data.actDes.storeId
            })
        // }
    },
    // onShareAppMessage: function () {
    //     return {
    //         title: this.data.title,
    //         imageUrl: this.data.posterImage
    //     }
    // },
    onShareAppMessage: function (res) {
        // if (res.from === 'button') {
        return {
            imageUrl: this.data.posterImage,
            title: this.data.title,
            path: '/packageB/pages/Activity/actDes/index?id=' + this.data.actId + '&xpoint=' + this.data.lon + '&ypoint=' + this.data.lat,

            success: function (res) {
                // console.log('成功', res)
            }
        }
        // }
    },

    onShareTimeline() {

        let id = this.data.actId
        let xpoint = this.data.lon
        let ypoint = this.data.lat

        let data = {
            query: 'id=' + id
                + '&xpoint=' + xpoint
                + '&ypoint=' + ypoint
                + this.getActDes()

            ,
            imageUrl: this.data.posterImage,
            title: this.data.title
        }
        return data

    }
})